package com.example.forum.controller;

import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author YJ
 * @Date 2023/8/18 8:52
 * Description:
 */
@Slf4j
@Api(tags = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IBoardService boardService;
    @Resource
    private IArticleService articleService;

    /**
     * 发布新帖
     *
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam(value = "板块Id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam(value = "文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam(value = "文章内容") @RequestParam("content") @NonNull String content) {
        //校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            //用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Board board = boardService.selectById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //返回响应
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //封装文章对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        articleService.create(article);
        return AppResult.success();
    }

    @ApiOperation("查询帖子列表")
    @GetMapping("/selectAllByBoardId")
    public AppResult<List<Article>> selectAllByBoardId(@ApiParam(value = "板块Id") @RequestParam(value = "boardId", required = false) Long boardId) {
        //定义返回的集合
        List<Article> articles;
        if (boardId == null) {
            //没有传参时
            articles = articleService.selectAll();
            if (articles == null) {
                articles = new ArrayList<>();
            }
        } else {
            //传递了board参数
            articles = articleService.selectAllByBoardId(boardId);
        }
        if (articles == null) {
            articles = new ArrayList<>();
        }

        //相应结果
        return AppResult.success(articles);
    }

    @ApiOperation("根据帖子查询详情")
    @GetMapping("/getDetails")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam(value = "帖子Id") @RequestParam("id") @NonNull Long id) {
        //从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);


        //调用service获取帖子详情
        Article article = articleService.selectDetailById(id);
        //判断结果是否为空
        if (article == null) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断当前用户是否为作者
        if (user.getId() == article.getUserId()) {
            //标识为作者
            article.setOwn(true);
        }

        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam(value = "帖子Id") @RequestParam("id") @NonNull Long id,
                            @ApiParam(value = "帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam(value = "帖子内容") @RequestParam("content") @NonNull String content) {
        //获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getState() == 1) {
            //返回错误描述
            //用户为禁言状态
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        //校验帖子是否存在
        if (article == null) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断用户是不是作者
        if (user.getId() != article.getUserId()) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //判断帖子状态
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //调用service
        articleService.modify(id, title, content);
        //打印日志
        log.info("帖子更新成功. Article id = " + id + "User id = " + user.getId() + ".");
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("点赞帖子")
    @PostMapping("/thumbsUpById")
    public AppResult thumbsUpById(HttpServletRequest request,
                                  @ApiParam(value = "帖子Id") @RequestParam("id") @NonNull Long id) {
        //校验用户状态（是否禁言）
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断session是否有效
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //调用service
        articleService.thumbsUpById(id);
        //返回结果

        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/deleteById")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam(value = "帖子Id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            //用户禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        //校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断当前用户是否为作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.deleteById(id);
        //返回操作成功
        return AppResult.success();
    }

    @ApiOperation("根据用户id查询帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam(value = "用户Id") @RequestParam(value = "userId", required = false) Long userId) {
        //如果UserId为空，从session中获取登陆用户的id
        if (userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //调用service
        List<Article> articles = articleService.selectByUserId(userId);

        return AppResult.success(articles);
    }
}
